﻿using SpeakToMe.Core.Enums;
using SpeakToMe.Speech.Tokens;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;

namespace SpeakToMe.Speech.Questions
{
    [Export]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class QuestionManager
    {
        private List<Question> ActiveQuestions { get; set; }

        /// <summary>
        /// Initializes a new instance of the QuestionManager class.
        /// </summary>
        public QuestionManager()
        {
            this.ActiveQuestions = new List<Question>();
        }

        public void CheckForMatchingQuestion(Dictionary<int, List<TokenResult>> buckets, ConversationType mode, int userId, string address, ref Question matchedQuestion, ref List<Token> tokens)
        {
            bool matchedAll = true;
            foreach (var question in this.ActiveQuestions.OrderByDescending(q => q.PosedDateTime))
            {
                int index = 0;
                foreach (var expectedType in question.ExpectedReplys)
                {
                    Type searchType = expectedType.GetType();

                    TokenResult token = null;

                    if (buckets.Any())
                    {
                        token = (from t in buckets.ElementAt(index).Value
                                 where
                                      t.Token.GetType() == searchType ||
                                      t.Token.GetType().IsSubclassOf(searchType)
                                 select t).FirstOrDefault();

                        if (token != null)
                        {
                            matchedAll = true;
                            tokens.Add(token.Token);
                        }
                        else
                        {
                            matchedAll = false;
                            tokens.Clear();
                            break;
                        }
                    }

                    index++;
                }

                if (matchedAll)
                {
                    matchedQuestion = question;
                    return;
                }
                else
                {
                    matchedQuestion = null;
                }
            }
        }

        public void AddQuestion(Question question)
        {
            this.ActiveQuestions.Add(question);
        }

        public void RemoveQuestion(Question question)
        {
            this.ActiveQuestions.Remove(question);
        }
    }
}